package com.zrt.pad.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;

import com.zrt.pad.commonui.SharedApplication;
import com.zrt.pad.datasource.db.CustomDBHelper;

public class DBUtil {

	public void backupDb() throws Exception{
		Context c = SharedApplication.context;
		File db = c.getDatabasePath(CustomDBHelper.name);
		File dest = new File(Environment.getExternalStorageDirectory().getPath(),"backup.db");
		if (!dest.exists()) {
			try {
				dest.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(db);
			fos = new FileOutputStream(dest);
			byte[] buffer = new byte[10240];
			while (true) {
				int length = fis.read(buffer);
				if (length == -1) {
					break;
				}
				fos.write(buffer, 0, length);
			}
			
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void restoreDb() throws Exception{
		Context c = SharedApplication.context;
		File dest = c.getDatabasePath(CustomDBHelper.name);
		File db = new File(Environment.getExternalStorageDirectory().getPath(),"backup.db");
		if (!dest.exists()) {
			throw new Exception("不能读取系统数据库文件！");
		}
		if (!db.exists()) {
			throw new Exception("未找到要还原的数据库文件�?");
		}
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(db);
			fos = new FileOutputStream(dest);
			byte[] buffer = new byte[10240];
			while (true) {
				int length = fis.read(buffer);
				if (length == -1) {
					break;
				}
				fos.write(buffer, 0, length);
			}
			
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
